package com.sobot.finance.poc.web.util;

import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import com.google.gson.Gson;
import com.sobot.finance.poc.web.config.SysConfig;
import com.sobot.finance.poc.web.controller.response.GeneralRes;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * API
 *
 * @author baiyp
 */
@Slf4j
@Component
public class PocClient {

    @Resource
    private SysConfig sysConfig;

    /**
     * 线程安全
     */
    protected static Gson gson = new Gson();

    /**
     * 默认类型
     */
    private static final String CONTENT_TYPE = "application/json;charset=utf-8";

    /**
     * 超时时间：毫秒
     */
    private static final int TIME_OUT = 60_000;

    public boolean callback(Object param) {
        log.info("[推送-开始]: {}", gson.toJson(param));
        boolean success = false;
        try {
            // 请求
            String result = HttpRequest.post(sysConfig.getCallbackUrl())
                    .header(Header.CONTENT_TYPE, CONTENT_TYPE)
                    .body(gson.toJson(param))
                    .timeout(TIME_OUT)
                    .execute()
                    .body();

            log.info("[result]: {}", gson.toJson(result));

            GeneralRes res = gson.fromJson(result, GeneralRes.class);

            if (Objects.nonNull(res) && res.succeed()) {
                success = true;
            }
        } catch (Exception e) {
            log.error("[异常]: ", e);
        }
        log.info("[推送-结束]: {}", gson.toJson(success));
        return success;
    }

    public boolean manualCallback(String json) {
        log.info("[推送-开始]: {}", json);
        boolean success = false;
        try {
            // 请求
            String result = HttpRequest.post(sysConfig.getCallbackUrl())
                    .header(Header.CONTENT_TYPE, CONTENT_TYPE)
                    .body(json)
                    .timeout(TIME_OUT)
                    .execute()
                    .body();

            log.info("[result]: {}", gson.toJson(result));

            GeneralRes res = gson.fromJson(result, GeneralRes.class);

            if (Objects.nonNull(res) && res.succeed()) {
                success = true;
            }
        } catch (Exception e) {
            log.error("[异常]: ", e);
        }
        log.info("[推送-结束]: {}", gson.toJson(success));
        return success;
    }
}
